<template>
	<div id="contract_drawer">
		<el-row style="padding:10px  15px">
				<el-col :span="22" class="customName">{{ contract.theme }}</el-col>
				<el-col :span="2" class="more">
					<el-dropdown :hide-on-click="false" trigger="click" @command="handleCommand">
						<span class="el-dropdown-link">
							<i class="iconfont icon-m-weixinwenzhang"></i>
						</span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item command="a">查看</el-dropdown-item>
							<el-dropdown-item command="b">编辑</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</el-col>
			</el-row>

			<hr class="hr2" style="margin: 3px;" />
			<!-- 合同产品 -->
			<el-tabs v-model="activeNameDetail" type="card">
				<el-tab-pane label="产品" name="first">
					<div style="margin:5px">
						<div class="actP" v-for="pro in contract.productList" :key="pro.proDetailId">
							<table>
								<tbody>
									<tr>
										<td rowspan="3" class="pi">
											<el-image :src="pro.proDetail.proImgSrc"></el-image>
										</td>
										<td colspan="2" class="pn">
											{{pro.proDetail.product.proClassily.proClassilyName}}
											<i class="fa fa-angle-right"></i>
											{{pro.proDetail.product.productName}}
											<span v-for="ability in pro.proDetail.abilities" :key="ability.abilityId">
												<i class="fa fa-angle-right" ></i>
												{{ ability.abilityName }}
											</span>
										</td>
									</tr>
									<tr>
										<td style="width: 50%;">数量：{{pro.proCount}}</td>
										<td>单价：{{pro.discount}}</td>
									</tr>
									<tr>
										<td>品牌：{{pro.proDetail.product.productBrand}}</td>
										<td>总额：{{pro.discount*pro.proCount}}</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
				</el-tab-pane>
				<!-- 合同应收列表 -->
				<el-tab-pane label="应收" name="second">
					<div class="receipt">
						<table style="width:100%" v-if="contract.conState.id!=1">
							<tbody>
								<tr>
									<td>
										<el-input placeholder="请输入回款金额" v-model="returnmon.returnMoney"></el-input>
									</td>
								</tr>
								<tr>
									<td>
										<el-date-picker
											v-model="returnmon.returnDate"
											placeholder="请选择回款日期"
											type="date"
											style="width:100%"
                                            :picker-options="returnDatePicker"
										></el-date-picker>
									</td>
								</tr>
								<tr>
									<td style="text-align: right;">
										<div style="float: left;">
											<el-button
												type="success"
												plain
												@click="openBackToArticleRecordDialog"
											>添加详细的回款计划</el-button>
										</div>
										<div style="float: right;">
											<el-button type="primary" plain @click="addReturnmon">保存</el-button>
										</div>
									</td>
								</tr>
							</tbody>
						</table>
						<!-- 没有应收信息 -->
						<div v-if="returnmons.length == 0">
							<div class="alert alert-danger">未建立应收款信息！</div>
						</div>
						<!-- 有应收信息 -->
						<div :class="['actB',r.isReturn==1?'green':'red' ]" v-for="r in returnmons" :key="r.returnId">
							<div class="t">
								<div style="float: left;">{{ r.returnMoney }}元</div>
								<div style="float: right;">{{ r.returnDate | format_date }}</div>
								<div style="clear:both;"></div>
							</div>
							<div class="ct">{{ r.isReturn==1?"已回款":"尚未回款" }}
								<span style="float: right;">{{ r.returnTimes.name }}</span>
							</div>
							<hr class="hr2" />
							<div class="ft" v-if="r.isReturn!=1">
								<el-button type="danger" circle @click="editReturnmon(r)">收</el-button>
								<el-button type="success" circle @click="addReturnRecord(r)">回</el-button>
							</div>
						</div>
					</div>
				</el-tab-pane>
				<!-- 回款列表 -->
				<el-tab-pane label="回款" name="third">
					<div id="contract_drawer_payment" style="width: 95%; margin:10px auto;">
						<hr class="hr2" />
						<div style="margin:0 5px;">
							<!-- 没有回款金额 -->
							<div v-if="returnRecords.length==0">
								<div class="alert alert-danger">还没有回款记录！</div>
							</div>
							<!-- 回款记录 -->
							<div class="actB green" v-for="rr in returnRecords" :key="rr.returnRecordId">
								<div class="t">
									<div style="float: left;">{{rr.returnMoney}}元</div>
									<div style="float: right;">{{ rr.realReturnDate | format_date }}</div>
									<div style="clear:both;"></div>
								</div>
								<div class="ct">{{rr.remark?rr.remark:"没有详情描述"}}
									<span style="float: right;">{{ rr.returnmon.returnTimes.name }}</span>
								</div>
								<hr class="hr2" />
								<div class="ft" v-if="rr.takeInvoice==2">
									<el-button type="success" circle @click="addInv(rr)" >票</el-button>
								</div>
							</div>
						</div>
					</div>
				</el-tab-pane>
				<!-- 发票列表 -->
				<el-tab-pane label="发票" name="fourth">
					<div style="width: 95%; margin:10px auto;">
						<table style="width: 100%;" v-if="contract.conState.id!=1">
							<tbody>
								<tr>
									<td>
										<el-input v-model="conInvoice.invCon" placeholder="请输入开票内容"></el-input>
									</td>
								</tr>
								<tr>
									<td>
										<el-input v-model="conInvoice.invMoney" placeholder="请输入开票金额"></el-input>
									</td>
								</tr>
								<tr>
									<td>
										<el-date-picker
											v-model="conInvoice.invBeginDate"
											placeholder="请选择开票日期"
											type="date"
											style="width:100%"
										></el-date-picker>
									</td>
								</tr>
								<tr>
									<td>
										<el-select v-model="conInvoice.invType" value-key="id" style="width:100%!important" placeholder="请选择发票类型">
											<el-option v-for="item in invoiceType" :key="item.id" :label="item.name" :value="item"></el-option>
										</el-select>
									</td>
								</tr>
								<tr>
									<td style="text-align: right;">
										<div style="float: right;">
											<el-button type="primary" plain @click="savaConIvoice">保存</el-button>
										</div>
									</td>
								</tr>
							</tbody>
						</table>
						<hr class="hr2" />
						<div style="margin:0 5px;">
							<!-- 没有开票金额 -->
							<div v-if="conInvoiceRecords.length == 0">
								<div class="alert alert-danger">还没有开票记录！</div>
							</div>
							<!-- 开票记录 -->
							<div class="actB purple" v-for="ir in conInvoiceRecords" :key="ir.conInvoiceRecId">
								<div class="t">
									<div style="float: left;">{{ir.invMoney}}元</div>
									<div style="float: right;">{{ ir.invBeginDate | format_date }}</div>
									<div style="clear:both;"></div>
								</div>
								<div class="ct">
									<span class="fl">{{ ir.invType.name }}</span>
									<span class="fr">{{ ir.invCon }}</span>
								</div>
								<hr class="hr2" />
								<!-- <div class="ft">
									<el-button type="warning" circle @click="editInv(ir)">改</el-button>
								</div> -->
							</div>
						</div>
					</div>
				</el-tab-pane>
			</el-tabs>
	</div>
</template>

<script>
import {formatTimeToStr} from "../../assets/format"

export default {
	name: "contractDrawer",
	props:["contract"],
	data(){
		return {
			activeNameDetail: "first",	//抽屉中tabs导航标识
			// 发票类型
			invoiceType: [],
			// 发票类型选中值
			invoiceTypeValue: '',
			paymentDate: '',		//回款日期
			returnmon:{				// 回款计划表单数据
				principal:this.$store.state.user,
				isReturn:2,
			},	
			conInvoice:{					// 开票记录对象
				invBeginDate:new Date(),	// 开票日期
				isReturnMon:2,				// 是否回款
				handleEmp:this.$store.state.user
			},		

			returnmons:[],		// 回款计划列表
			returnRecords:[],	// 回款记录列表
			conInvoiceRecords:[],// 开票记录列表
            // 日期限定
            returnDatePicker:{
				disabledDate(time){
					return time.getTime() < Date.now() - 8.64e7
				}
			}
			
		}
	},
	methods:{
		// 修改回款记录
		editReturnRecord(rr){
			this.$parent.$parent.backToArticleRecordDialogVisible = true
			this.$nextTick(function(){
				this.$parent.$parent.$refs.refBackToArticleRecord.returnRecord = this.global.copy_obj(rr)
				this.$parent.$parent.$refs.refBackToArticleRecord.returnMon = this.global.copy_obj(rr.returnmon)
			})
		},
		// 从回款记录开票
		addInv(rr){
			this.$parent.$parent.conInvoiceRecordDialogVisible = true
			this.$nextTick(function(){
				this.$parent.$parent.$refs.refConInvoiceRecord.conInvoice.invMoney = rr.returnMoney
				this.$parent.$parent.$refs.refConInvoiceRecord.conInvoice.isReturnMon = 1
				this.$parent.$parent.$refs.refConInvoiceRecord.returnRecord = this.global.copy_obj(rr)
				this.$parent.$parent.$refs.refConInvoiceRecord.isDrawer = true
			})
		},
		// 修改开票记录
		editInv(ir){
			this.$parent.$parent.conInvoiceRecordDialogVisible = true
			this.$nextTick(function(){
				this.$parent.$parent.$refs.refConInvoiceRecord.conInvoice = this.global.copy_obj(ir)
			})
		},
		// 快捷添加开票记录
		savaConIvoice(){
			// 校验数据
			if(!this.conInvoice.invCon || !this.conInvoice.invMoney || !this.conInvoice.invType || !this.conInvoice.invType){
				this.global.mes_error("数据不完整，请填写后再提交")
				return
			}
			const loading = this.$loading({
				lock: true,
				text: '保存中',
				spinner: 'el-icon-loading',
				background: 'rgba(0,0,0,0.5)'
			})
			this.conInvoice.contract = this.contract
			this.axios.post("api/in-sale/conInvoice",this.conInvoice)
			.then(async res => {
				this.initData()
				loading.close()
				this.global.mes_success("开票记录保存成功")
			})
			.catch(err => {
				loading.close()
				this.global.mes_error("开票记录保存失败，请稍后再试！")
			})
		},
		// 快捷添加回款计划
		async addReturnmon(){
			// 计算期次
			const res = await this.axios.get("api/dd/return_times")
			// 回款期次
			let returnTimes = res.data
			let i = returnTimes.length
			while (i--) {
				for (let j = 0; j < this.returnmons.length; j++) {
					if(this.returnmons[j].returnTimes.id == returnTimes[i].id){
						returnTimes.splice(i,1)
					}					
				}
			}
			this.returnmon.returnTimes = returnTimes[0]
			window.console.log(this.returnmon);
			// 验证数据
			if(!this.returnmon.returnMoney){
				this.global.mes_error("请填写回款金额")
				return
			}
			if(!this.returnmon.returnDate){
				this.global.mes_error("请填写回款时间")
				return
			}
			if(parseInt(this.returnmon.returnMoney) + this.contract.returnMoney > this.contract.totalMoney){
				this.global.mes_error("回款金额超出")
				return
			}
			
			// 将合同对象赋值给returnMon
			this.returnmon.contract = this.contract
			const loading = this.$loading({
				lock: true,
				text: '保存中',
				spinner: 'el-icon-loading',
				background: 'rgba(0,0,0,0.3)'
			});
			// 发送请求
			this.axios.post("api/in-sale/return-mon",this.returnmon)
			.then(res => {
				loading.close()
				this.global.mes_success("回款计划保存成功")
				this.initData()
			})
			.catch(err => {
				loading.close()
				this.global.mes_error("回款计划保存失败，请稍后再试！")
				console.error(err); 
			})
			
		},
		// 添加回款记录
		addReturnRecord(r){
			this.global.confirm("提示","确认回款？",
			() => {
				let returnRecord = {				// 回款记录数据源
					realReturnDate:new Date(),
					takeInvoice:2,
					paymentMethod:this.contract.paymentMethod,
					principal:this.$store.state.user
				}
				// 将回款计划 加入记录中
				returnRecord.returnmon = r
				// 将合同 加入记录对象中
				returnRecord.contract = this.contract
				// 金额修改
				returnRecord.returnMoney = r.returnMoney
				const loading = this.$loading({
					lock: true,
					text: '保存中',
					spinner: 'el-icon-loading',
					background: 'rgba(0,0,0,0.5)'
				});
				this.axios.post("api/in-sale/returnRecord", returnRecord)
				.then(res => {
					loading.close()
					this.global.mes_success("回款记录保存成功")
					this.initData()
				})
				.catch(err => {
					loading.close()
					this.global.mes_error("回款记录保存失败，请稍后再试！")
				})
			},() => {
				this.global.mes_message("取消回款")
			})
			
		},
		// 编辑回款计划
		editReturnmon(r){
			this.$parent.$parent.backToArticlePlanDialogVisible = true
			this.$nextTick(function(){
				this.$parent.$parent.$refs.refBackToArticlePlan.returnMon = this.global.copy_obj(r)
				this.$parent.$parent.$refs.refBackToArticlePlan.isDrawer = true
			})
		},
		// 更多的下拉菜单
		handleCommand(command) {
			if (command == 'a'){
				sessionStorage.setItem("contract", JSON.stringify(this.contract))
				this.$router.push({path:"/contract-details"})
			}else if (command == 'b') {
				// 打开新增弹框		编辑
				this.$parent.$parent.savaContractDialogVisible = true
				setTimeout(() => {
					// 拷贝一个合同临时对象
					let _contract = this.global.copy_obj(this.contract)
					// 处理开始和结束时间
					_contract.startTime = [formatTimeToStr(_contract.startTime,"yyyy-MM-dd"),
						formatTimeToStr(_contract.overTime,"yyyy-MM-dd")]
					// 处理签约时间
					_contract.signTime = formatTimeToStr(_contract.signTime,"yyyy-MM-dd")
					// 赋值对象
					this.$parent.$parent.$refs.refSaveContract.contract = _contract
				}, 50);
			} 
		},
		/* 打开新增回款记录弹窗 */
		openBackToArticleRecordDialog(){
			this.$parent.$parent.backToArticlePlanDialogVisible = true
			this.$nextTick(function(){
				this.$parent.$parent.$refs.refBackToArticlePlan.returnmons = this.returnmons
				this.$parent.$parent.$refs.refBackToArticlePlan.isDrawer = true
			})
		},
		/*  初始化数据 */
		initData(){
			// 根据合同id获取所有回款计划
			this.axios.get("api/in-sale/return-mon/"+this.contract.contractId)
			.then(res => {
				this.returnmons = res.data
			})
			.catch()
			// 根据合同id获取所有的回款记录
			this.axios.get("api/in-sale/returnRecord/"+this.contract.contractId)
			.then(res => {
				this.returnRecords = res.data
			})
			.catch(err => {
				console.error(err); 
			})
			// 根据合同id获取所有的开票记录
			this.axios.get("api/in-sale/conInvoiceRecord/"+this.contract.contractId)
			.then(res => {
				this.conInvoiceRecords = res.data
			})
			.catch(err => {
				console.error(err); 
			})
			// 获取票据类型列表
			this.axios.get("api/dd/invType")
			.then(res => {
				this.invoiceType = res.data
			})
			.catch(err => {
				this.global.mes_error("获取数据失败！")
			})
		}
	},
	created(){
		this.initData()
	}
}
</script>

<style scoped>

.customName{font-family: Microsoft YaHei, SimSun;font-weight: bold;font-size: 16px;padding-left: 12px;line-height: 21px;color: #636e7b;}
.more{font-size: 16px;color: black;line-height: 21px}
.actP {border-radius: 10px;border: solid 1px #dedede;padding: 10px;margin-bottom: 10px;}
.actP table {width: 100%;background-color: transparent;border-spacing: 0;border-collapse: collapse;border-width: 0;}
table td {padding: 5px;}
.actP .pi {vertical-align: top;}
.actP .el-image {width: 40px;height: 40px;border-radius: 50%;vertical-align: middle;border: 0;}
.actP .pn {border-bottom: #ddd 1px solid;font-size: 1.2em;font-weight: bold;}
.actP .pn i {padding: 0px 6px;}
.red {border-left: solid 10px #e75945;}
.actB {padding: 0px 10px 0px 0px;margin-bottom: 10px;}
.actB .t {padding-left: 10px;font-weight: bold;font-size: 16px;	border-top: solid 1px #eee;	padding-top: 10px;}
.actB .ct {	padding: 10px 10px;}
.actB hr {margin-bottom: 5px;margin-top: 0px;}
.hr2 {background-color: #eeeeee;height: 1px;border-width: 0px;width: 100%;}
.actB .ft {padding: 0px 0px 5px 10px;text-align: right;	border-bottom: 1px solid #eee;}
.receipt{margin: 20px 25px;}
.alert-danger {color: #a94442;background-color: #f2dede;border-color: #ebccd1;border-radius: 3px;}
.alert {padding: 15px;margin-bottom: 20px;border: 1px solid transparent;border-radius: 4px;}
.green {border-left: solid 10px #8dc059;}
.purple {border-left: solid 10px #967dd9;}
.el-dropdown-link{color:#606266 !important;}
.fl{float: left;}
.fr{float: right;}
</style>